package com.xinbochuang.machine.admin.controller.system;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinbochuang.machine.admin.domain.system.SysStorehouseOther;
import com.xinbochuang.machine.admin.domain.system.SysStorehouseOut;
import com.xinbochuang.machine.admin.domain.system.SysStorehouseOutSecond;
import com.xinbochuang.machine.admin.domain.vo.OutList;
import com.xinbochuang.machine.admin.service.system.ISysStorehouseOtherService;
import com.xinbochuang.machine.admin.service.system.ISysStorehouseOutSecondService;
import com.xinbochuang.machine.admin.service.system.ISysStorehouseOutService;
import com.xinbochuang.machine.common.controller.BaseController;
import com.xinbochuang.machine.common.domain.TableDataInfo;
import com.xinbochuang.machine.common.utils.AESUtils;
import com.xinbochuang.machine.common.utils.SecurityUtils;
import com.xinbochuang.machine.common.utils.poi.ExcelUtil;
import com.xinbochuang.machine.framework.web.domain.AjaxResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author 黄晓鹏
 * @date 2020-09-29
 */
@RestController
@RequestMapping("/system/storehouse-out")
public class SysStorehouseOutController extends BaseController {

    @Resource
    private ISysStorehouseOutService storehouseOutService;

    @Resource
    private ISysStorehouseOtherService otherService;

    @Resource
    private ISysStorehouseOutSecondService outSecondService;

    /**
     * 出库列表
     *
     * @param storehouseOut 出库
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysStorehouseOut storehouseOut) {
        startPage();
        return getDataTable(storehouseOutService.selectList(storehouseOut));
    }

    /**
     * 查询出库详细
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:query')")
    @GetMapping(value = "/{outId}")
    public AjaxResult getInfo(@PathVariable Integer outId) {
        return AjaxResult.data(storehouseOutService.selectById(outId));
    }

    /**
     * 新增出库
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:add')")
    @PostMapping
    public AjaxResult add(@RequestBody OutList outList) {
        return toAjax(storehouseOutService.insertStorehouseOut(outList));
    }

    /**
     * 修改出库
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody SysStorehouseOut storehouseOut) {
        storehouseOut.setUpdateBy(SecurityUtils.getUsername());
        storehouseOut.setUpdateTime(DateUtil.now());
        return toAjax(storehouseOutService.updateStorehouseOut(storehouseOut));
    }

    /**
     * 删除出库
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(storehouseOutService.deleteByIds(ids));
    }


    /**
     * 修改出库状态
     */
    @PreAuthorize("@ss.hasAnyPermi('system:storehouse-in:check,system:storehouse-in:pass')")
    @PutMapping("/changeStatus")
    public AjaxResult check(@RequestBody SysStorehouseOut storehouseOut) {
        if(storehouseOut.getStatus().equals("6")){
            storehouseOut.setStatus("5");
        }
        return toAjax(storehouseOutService.updateStatus(storehouseOut));
    }

    /**
     * 根据计划编号获取详细信息
     */
    @GetMapping(value = "/getStoreOutList")
    public TableDataInfo getStoreOutList(SysStorehouseOut storehouseOut) {
        return getDataTable(storehouseOutService.getStoreOutList(storehouseOut));
    }

    /**
     * 根据计划编号获取详细信息
     */
    @GetMapping(value = "/getStoreOutListN")
    public AjaxResult getStoreOutListN(SysStorehouseOut storehouseOut) {
        return AjaxResult.data(AESUtils.encode(JSON.toJSONStringWithDateFormat(getDataTable(storehouseOutService.getStoreOutList(storehouseOut)),"yyyy-MM-dd HH:mm:ss")));
    }

    /**
     * 根据计划编号获取详细信息
     */
    @GetMapping(value = "/getOutDetailByQrCode")
    public AjaxResult getOutDetailByQrCode(@RequestParam("qrcode") String qrcode) {
        SysStorehouseOther sysStorehouse = storehouseOutService.getOutDetailByQrCode(qrcode);
        if (sysStorehouse == null) {
            return AjaxResult.error();
        }
        return AjaxResult.data(sysStorehouse);
    }

    /**
     * 根据计划编号获取详细信息
     */
    @GetMapping(value = "/getOutDetailByQrCodeN")
    public AjaxResult getOutDetailByQrCodeN(@RequestParam("qrcode") String qrcode) {
        SysStorehouseOther sysStorehouse = storehouseOutService.getOutDetailByQrCode(qrcode);
        if (sysStorehouse == null) {
            return AjaxResult.error();
        }
        return AjaxResult.data(AESUtils.encode(JSON.toJSONStringWithDateFormat(sysStorehouse,"yyyy-MM-dd HH:mm:ss")));
    }

    /**
     * 根据计划编号获取详细信息
     */
    @GetMapping(value = "/output")
    public AjaxResult output(@RequestParam("id") String id) {
        storehouseOutService.output(id);
        return AjaxResult.data("");
    }


    /**
     * 根据入库id查询一级/二级清单
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:list')")
    @GetMapping("/getDetailList")
    public AjaxResult getDetailList(Integer outId) {
        List<SysStorehouseOther> storehouseList = otherService.list(Wrappers.<SysStorehouseOther>lambdaQuery().eq(SysStorehouseOther::getOutId, outId));
        for (SysStorehouseOther storehouse : storehouseList) {
            storehouse.setChildren(outSecondService.list(Wrappers.<SysStorehouseOutSecond>lambdaQuery().eq(SysStorehouseOutSecond::getFirstId, storehouse.getId())));
        }
        return AjaxResult.data(storehouseList);
    }


    @RequestMapping("/getExcel")
    @ResponseBody
    public AjaxResult getUserExcel(HttpServletResponse response, SysStorehouseOut storehouseOut) {
        try {
            ServletOutputStream out = response.getOutputStream();
//            String fileName=new String(("yhgs").getBytes(),"UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("出库待办列表" + ".xls", "UTF-8"));
            storehouseOutService.excelExport(out, storehouseOut);
        } catch (Exception e) {

        }
        return AjaxResult.ok();
    }

//    public ResponseEntity<FileSystemResource> export(String filePath) {
//        File file=new File(filePath);
//        if (file == null) {
//            return null;
//        }
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
//        headers.add("Pragma", "no-cache");
//        headers.add("Expires", "0");
//        headers.add("Last-Modified", new Date().toString());
//        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
//
//        return ResponseEntity
//                .ok()
//                .headers(headers)
//                .contentLength(file.length())
//                .contentType(MediaType.parseMediaType("application/octet-stream"))
//                .body(new FileSystemResource(file));
//    }

    /**
     * 导出待办
     */
    @PreAuthorize("@ss.hasPermi('system:storehouse-out:export')")
    @GetMapping("/export")
    public AjaxResult export(SysStorehouseOut storehouseOut) {
        List<SysStorehouseOut> list = storehouseOutService.selectExportList(storehouseOut);
        ExcelUtil<SysStorehouseOut> util = new ExcelUtil<>(SysStorehouseOut.class);
        return util.exportExcel(list, "出库待办");
    }

}

